/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package muhnes.sizoo.dal;


import java.util.List;
import javax.annotation.PreDestroy;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import muhnes.sizoo.HibernateUtilZoologia;
import muhnes.sizoo.modelo.Animal;
/**
 *
 * @author CALDERON
 */
public class AnimalDaoImpl implements AnimalDao {
     Session sesion;
    
    public AnimalDaoImpl() {
        sesion = HibernateUtilZoologia.getSessionFactory().openSession();
    }
    
    @PreDestroy
    public void destroy() {
        sesion.close();
    }

    @Override
    public void guardar( Animal animal ) {
        Transaction transaccion = sesion.beginTransaction();
       sesion.save( animal );
        transaccion.commit();
    }

        
    @Override
    public void guardarColeccion( List< Animal > animals ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.saveOrUpdate( animals );
        transaccion.commit();
    }

    @Override
    public void actualizar( Animal animal ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.update( animal );
        transaccion.commit();
    }

    @Override
    public void actualizarColeccion( List< Animal > animals ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.update( animals );
        transaccion.commit();
    }

    @Override
    public void eliminar( Animal animal ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.delete( animal );
        transaccion.commit();
    }

    @Override
    public void eliminarColeccion( List< Animal > animals ) {
        Transaction transaccion = sesion.beginTransaction();
        sesion.delete( animals );
        transaccion.commit();
    }

    @Override
    public void eliminarPorId( int id ) {
        Transaction transaccion = sesion.beginTransaction();
        Animal animal = buscarPorId( id );
        sesion.delete( animal );
        transaccion.commit();
    }

    @Override
    public Animal buscarPorId( int id ) {
        Transaction transaccion = sesion.beginTransaction();
        Query consulta = sesion.createQuery("from Animal where codigoanimal = " + id);
        Animal animal = (Animal)consulta.uniqueResult();
        transaccion.commit();
        return animal;
    }

    @Override
    public List< Animal > buscarTodos() {
        Transaction transaccion = sesion.beginTransaction();
        Query consulta = sesion.createQuery("from Animal");
        List< Animal > animals = consulta.list();
        transaccion.commit();
        return animals;
    }

}
